/*
 * The MIT License 
 *
 * Copyright (c) 2010 pf-miles
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package me.wenyue.parambinder.impl;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import me.wenyue.parambinder.BindingContext;
import me.wenyue.parambinder.BindingMethod;
import me.wenyue.parambinder.BindingParameter;
import me.wenyue.parambinder.exception.ParamBinderException;

/**
 * DefaultBindingMethod.java
 * 
 * @author pf-miles 2010-9-28 下午07:11:52
 * 
 */
public class DefaultBindingMethod implements BindingMethod {
    // the underlying method's lexical name
    private String name;
    private List<BindingParameter> params = new ArrayList<BindingParameter>();
    private Class<?> returnType;
    // the underlying method, XXX use 'fast method' instead?
    private Method method;

    public List<Object> bind(BindingContext context) {
        List<Object> ret = new ArrayList<Object>();
        if (params != null)
            for (BindingParameter p : params) {
                ret.add(p.drainValueFrom(context));
            }
        return ret;
    }

    @SuppressWarnings("unchecked")
    public <T> T bindAndInvoke(BindingContext context, Object obj) throws ParamBinderException {
        return (T) invoke(obj, bind(context));
    }

    @SuppressWarnings("unchecked")
    public <T> T invoke(Object obj, List<Object> args) throws ParamBinderException {
        // if params is empty, invoke the method with no args directly
        if (params == null || params.isEmpty()) {
            try {
                return (T) method.invoke(obj);
            } catch (Exception e) {
                throw new ParamBinderException("Method: '" + name + "' invoke error!", e);
            }
        }

        // if params is not empty but the args are null or empty, exception...
        if (args == null || args.isEmpty()) {
            StringBuilder sb = buildParamsMsg();
            sb.append(", but given a list of null or empty!");
            throw new ParamBinderException(sb.toString());
        }

        // if params length not equal to args length, exception...
        if (params.size() != args.size()) {
            StringBuilder sb = buildParamsMsg();
            sb.append(", but given a list of length ").append(args.size()).append(": [");
            Iterator<Object> iter = args.iterator();
            for (int i = 1; iter.hasNext(); i++) {
                Object v = iter.next();
                sb.append(v);
                if (i != args.size())
                    sb.append(", ");
            }
            sb.append("].");
            throw new ParamBinderException(sb.toString());
        }
        try {
            return (T) this.method.invoke(obj, args.toArray());
        } catch (Exception e) {
            throw new ParamBinderException("Method: '" + name + "' invoke error!", e);
        }
    }

    private StringBuilder buildParamsMsg() {
        StringBuilder sb = new StringBuilder();
        sb.append("The param list of method '");
        sb.append(name);
        sb.append("' is expected to be a list of length ");
        sb.append(params.size());
        sb.append(": [");
        Iterator<BindingParameter> pIter = params.iterator();
        for (int i = 1; pIter.hasNext(); i++) {
            BindingParameter p = pIter.next();
            sb.append(p.getParameterClass().getName());
            if (i != params.size())
                sb.append(", ");
        }
        sb.append("]");
        return sb;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setParams(List<BindingParameter> params) {
        this.params = params;
    }

    public void setReturnType(Class<?> returnType) {
        this.returnType = returnType;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

}
